#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Copyright 2013 suliu.net
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#codeby     道长且阻
#email      ydhcui@suliu.net/QQ664284092
#website    http://www.suliu.net

import random
import json
import hashlib
import os
import sys
import time
import threading
import pickle
import re
import gzip

try:
  import urllib as parse
  import urllib2 as request
  import cookielib as cookiejar
except ImportError as e:
  #print(e)
  from urllib import parse,request
  from http import cookiejar

try:import util
except:pass

def pprint(*s):
    try:sys.stdout.write('\n'.join(s))
    except:print("coding error")


class LOGIN(object):
    js_ver = '10076'
    aid = '549000912'

    def getgtk(self,str):
        hash=5381
        for i in str:
            hash+=(hash<<5)+ord(i)
        return hash & 0x7fffffff
    def _hexchar2bin(self, num):
        arry = bytearray()
        for i in range(0, len(num), 2):
            arry.append(int(num[i:i+2],16))
        return arry
    def _preprocess(self, password=None, verifycode=None):
        self.__hashpasswd = self.md5(password) #store hashed password
        I = self._hexchar2bin(self.__hashpasswd)
        H = self.md5(I + bytes(verifycode[2], encoding="ISO-8859-1"))
        G = self.md5(H + verifycode[1].upper())
        return G
    def md5(self, s):
        try:s = s.encode('utf-8')
        finally:return hashlib.md5(s).hexdigest().upper()
    def _getverifycode(self):
        url = 'http://check.ptlogin2.qq.com/check?uin=%s&appid=%s&regmaster=&js_type=1&js_ver=%s&r=%s'%(self.qq, self.aid,self.js_ver, random.Random().random())
        res = self._request(url)
        verify =  list(eval(res.split("(")[1].split(")")[0]))
        if verify[0] == '1':
            img = "http://captcha.qq.com/getimage?aid=%s&uin=%s&cap_cd=%s&%s"%(self.aid,self.qq,verify[1],random.Random().random() )
            open(self.verifypath,"wb").write(self.opener.open(request.Request(img)).read())
            verify[1]=input("请输入%sQQ空间的验证码:"%self.qq).strip()
        return verify

    def _request(self, url, data=None, cookie=False):
        if data:rr = request.Request(url,parse.urlencode(data).encode('utf-8'),self._headers)
        else:rr = request.Request(url=url, headers=self._headers)
        fp=self.opener.open(rr)
        #for k,v in fp.info().items():
        #    print(k,v)
        if fp:
            if fp.info().get('Content-Encoding') == 'gzip':
                f = gzip.decompress(fp.read())
                try:res = f.decode('utf-8')
                except:res = f.decode('GBK')
            else:
                try:res = fp.read().decode('utf-8')
                except:res = fp.read()
            t = fp.info().get('Content-Type')
            if t == 'text/plain; charset=utf-8' or t == 'application/json;charset=utf-8':
                res = json.loads(res)
                if res['retcode'] == 0:res = res['result']
                else:res = None
            if cookie:
                self.cookieJar.save(ignore_discard=True, ignore_expires=True)
        return res

    def __init__(self, qq, pw):
        self.qq = qq
        self._pw = pw
        self.cookies = {}
        self.gtk=""
        self.cookiepath=util.getres("%sqzone.cookie"%self.qq)
        self.verifypath=util.getres("VFqzone.png")
        self.cookieJar = cookiejar.MozillaCookieJar(self.cookiepath)
        self.opener = request.build_opener(request.HTTPCookieProcessor(self.cookieJar))
        self._headers = {
            "User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:14.0) Gecko/20100101 Firefox/14.0.1",
            "Accept-Language":"zh-cn,en;q=0.8,en-us;q=0.5,zh-hk;q=0.3",
            "Accept-Encoding":"gzip;deflate",
            "Connection":"keep-alive"
            }
        self.login()

    def login(self):
        print('login...',self.qq)
        if os.path.isfile(self.cookiepath):
            self.cookieJar.load(ignore_discard=True, ignore_expires=True)
            pprint("登录成功%s\n"%self.qq)
        else:
        #if 1:
            self._verifycode = self._getverifycode()
            self.pswd = self._preprocess(self._pw, self._verifycode)
            self._headers.update({"Referer":"http://xui.ptlogin2.qq.com/cgi-bin/xlogin?proxy_url=http%3A//qzs.qq.com/qzone/v6/portal/proxy.html&daid=5&pt_qzone_sig=1&hide_title_bar=1&low_login=0&qlogin_auto_login=1&no_verifyimg=1&link_target=blank&appid=549000912&style=22&target=self&s_url=http%3A//qzs.qq.com/qzone/v5/loginsucc.html?para=izone&pt_qr_app=%E6%89%8B%E6%9C%BAQQ%E7%A9%BA%E9%97%B4&pt_qr_link=http%3A//z.qzone.com/download.html&self_regurl=http%3A//qzs.qq.com/qzone/v6/reg/index.html&pt_qr_help_link=http%3A//z.qzone.com/download.html"})
            url="http://ptlogin2.qq.com/login?u=%s&p=%s&verifycode=%s&aid=%s" %(self.qq,self.pswd,self._verifycode[1],self.aid) \
            +"&pt_rsa=0&ptredirect=0&u1=http%3A%2F%2Fqzs.qq.com%2Fqzone%2Fv5%2Floginsucc.html%3Fpara%3Dizone&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=4-27-1398951016107&js_ver=10076&js_type=1&login_sig=V9YSFXh6Lb8gVHlAIkZBwWZbiucnqLnt-GrR71YZPJzM9bYUekVK71zep0TqBFJI&aid=549000912&daid=5&pt_qzone_sig=1&"
            res = self._request(url=url)
            if res.find("登录成功") != -1:
                pprint("登录成功\n")
                #self.cookieJar.save(ignore_discard=True, ignore_expires=True)
            elif res.find("验证码不正确") != -1:
                pprint("验证码错误")
                self._getverifycode()
                self.login()
            else:
                pprint(res)
        cookiedict=dict([(x.name,x.value) for x in self.cookieJar])
        self.cookies.update(cookiedict)
        try:self.gtk=self.getgtk(cookiedict['skey'])
        except:pass#os.remove(self.cookiepath)

    def logout(self):pass
    def __del__(self):self.logout()

class QZONE(LOGIN):
    def send_taotao(self,msg):
        """发表心情"""
        url="http://taotao.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=%s" %self.gtk
        data={"who":1,
        "con":msg,
        'feedversion':'1',
        'ver':'1',
        'private':'0',
        'code_version':'1',
        'format':'fs',
        'out_charset':'UTF-8',
        'hostuin':self.qq}
        res=self._request(url,data)
        return res

    def add_msbg(self,uin,msg,msgid=None):
        """发表留言"""
        try:msg=msg.encode('gbk')
        except:pass
        url="http://m.qzone.qq.com/cgi-bin/new/add_msgb?ref=qzone&g_tk=%s" %self.gtk
        data={'qzreferrer':'http://ctc.qzs.qq.com/qzone/msgboard/msgbcanvas.html#page=1',
              'content':msg,
              'hostUin':uin,
              'uin':self.qq,
              'format':'fs',
              'g_tk':self.gtk,
              'ref':'qzone',
              'json':'1',
              'inCharset':'utf8',
              'outCharset':'utf8',
              'iNotice':'1'
              }
        if msgid:
            data.update({'msgid':msgid})
        res=self._request(url,data)
        return res

    def get_friends(self):
        '''获取好友列表'''
        self._headers.update({'Referer':'http://ctc.qzs.qq.com/qzone/app/mood/friendsSelector.html'})
        url='http://r.qzone.qq.com/cgi-bin/tfriend/friend_show_qqfriends.cgi?uin=%s&follow_flag=1&groupface_flag=0&fupdate=1&g_tk=%s' %(self.qq,self.gtk)
        res=self._request(url)
        list=eval(res.replace('\n','').split(':[')[1].split('],')[0])
        return list
        """{"uin":231113,
            "groupid":0,
            "name":"乌龟哥哥",
            "remark":"备注",
            "img":"http://qlogo2.store.qq.com/qzone/231113/231113/30",
            "yellow":-1,
            "online":0,
            "v6":1}
        """

    def send_gift(self,uin,gifid='92555',message="哈哈哈哈"):
        """送礼物"""
        #[92555,92554,96946,83412,99572,96366]
        url="http://drift.qzone.qq.com/cgi-bin/sendgift?g_tk=%s" %self.gtk
        data={'qzreferrer':"http://cn.qzs.qq.com/qzone/gift/send_list.html?itemid=96946&uin=&source=0&giveback=0#html=send_single",
                'fupdate':1,
                'random':random.Random().random(),
                'charset':'utf-8',
                'uin':self.qq,
                'targetuin':uin,
                'source':'0',
                'nick':'sb',
                'giftid':gifid,
                'private':0,
                'giveback':'',
                'qzoneflag':1,
                'time':None,
                'timeflag':0,
                'giftmessage':message,
                'gifttype':0,
                'gifttitle':None,
                'newadmin':1,
                'clicksrc':None,
                'click_src_v2':'01|03|000|0000|0000|00',
                }
        res=self._request(url,data)
        return res

    def add_blog(self,title="title",html="message"):
        try:title=title.encode('gbk')
        except:pass
        try:html=html.encode('gbk')
        except:pass
        self._headers.update({'Origin':'http://ctc.qzs.qq.com'})
        url="http://b11.qzone.qq.com/cgi-bin/blognew/add_blog?g_tk%s"%self.gtk
        data={'qzreferrer':'http://ctc.qzs.qq.com/qzone/newblog/v5/editor.html' \
        +'#opener=refererurl&source=1&refererurl=http%3A%2F%2Fctc.qzs.qq.com%2F' \
        +'qzone%2Fapp%2Fblog%2Fv6%2Fbloglist.html%23nojump%3D1%26page%3D1%26catalog%3Dlist',
                'cate':'%B8%F6%C8%CB%C8%D5%BC%C7',
                'title':title,
                'html':html,
                'source':1,
                'blogType':0,
                'autograph':1,
                'topFlag':0,
                'feeds':1,
                'tweetFlag':0,
                'rightType':1,
                'uin':self.qq,
                'hostUin':self.qq,
                'iNotice':1,
                'inCharset':'gbk',
                'outCharset':'gbk',
                'format':'fs',
                'ref':'qzone',
                'json':1,
                'g_tk':self.gtk,
                'secverifykey':'28Q1206%s_%s'%(self.qq,self.qq)
            }
        res=self._request(url,data)
        return res

    def add_friend(self,uin,msg=None):
        url="http://w.qzone.qq.com/cgi-bin/tfriend/friend_addfriend.cgi?g_tk=%s" %self.gtk
        data={'qzreferrer':'http://ctc.qzs.qq.com/qzone/v6/friend_manage/addfriend/index.html#ouin=%s&sid=0&from=undefined'%uin,
            'sid':0,
            'ouin':uin,
            'uin':self.qq,
            'fupdate':1,
            'rd':random.Random().random(),
            'flag':0,
            'groupId':0,
            'chat':'',
            'key':'',
            'im':0,
            'g_tk':self.gtk
        }
        res=self._request(url,data)
        return res

    def get_msbg(self,uin,max=100):
        """获取留言"""
        msgblist=[]
        self._headers.update({"Referer":"http://ctc.qzs.qq.com/qzone/msgboard/msgbcanvas.html"})
        url="http://m.qzone.qq.com/cgi-bin/new/get_msgb?format=json&num=20&uin=%s&hostUin=%s&start=%s&s=%s&g_tk=%s"
        for start in range(0,max,20):
            res=json.loads(self._request(url%(self.qq,uin,start,random.Random().random(),self.gtk)))
            total=res['data']['total']
            commentlist = res['data']['commentList']
            if commentlist:msgblist += commentlist
            else:break
        return msgblist
        """{"id":"456",
            "pasterid":"",
            "bmp":" 8009c0002008001",
            "pubtime":"2013-10-24 16:37:16",
            "modifytime":0,
            "effect":0,
            "type":0,
            "uin":1985170374,
            "nickname":"WallE",
            "capacity":1599,
            "htmlContent":"少罗嗦，你还不如虫子呢！",
            "ubbContent":"少罗嗦，你还不如虫子呢！",
            "signature":"",
            "replyList":[]}
        """


    def get_blogid(self,uin):
        """获取日志id"""
        num=100 #一次获取的最大日志数
        self._headers.update({"Referer":"http://ctc.qzs.qq.com/qzone/app/blog/v6/bloglist.html"})
        url="http://b1.qzone.qq.com/cgi-bin/blognew/get_abs?hostUin=%s&uin=%s&blogType=0&cateName=&cateHex=&statYear=2013&reqInfo=5&pos=0&num=%s&sortType=0&absType=0&source=0&rand=%s&g_tk=%s&verbose=1&ref=qzone" %(uin,self.qq,num,random.Random().random(),self.gtk)
        res=self._request(url)
        try:
            return json.loads(res.split("back(")[1].split(");")[0])['data']['list']
        except:
            return [{'blogId'}]
        """{"blogId":1373279517,
            "blogType":0,
            "pubTime":"2013-07-08 18:31",
            "cate":"个人日记",
            "cateHex":"b8f6c8cbc8d5bcc7",
            "title":"少年",
            "commentNum":0,
            "effect1":512,
            "effect2":524294,
            "ar":0,
            "block":0,
            "inproc":false,
            "appeal":0}
        """

    def get_blogdata(self,uin,blogid):
        def find(source,startStr,endStr):
            source=str(source)
            try:
                start = source.index(startStr)
                source= source[start + len(startStr):]
                end   = source.index(endStr)
                data  = source[:end]
                return data
            except:
                return None
        url="http://b11.qzone.qq.com/cgi-bin/blognew/blog_output_data?uin=%s&blogid=%s&g_tk=%s"%(uin,blogid,self.gtk) \
        +"&styledm=ctc.qzonestyle.gtimg.cn&imgdm=ctc.qzs.qq.com&bdm=b.qzone.qq.com&mode=2&numperpage=15&property=GoRE&timestamp=&dprefix=&page=1&refererurl=http%3A%2F%2Fctc.qzs.qq.com%2Fqzone%2Fapp%2Fblog%2Fv6%2Fbloglist.html%23nojump%3D1%26page%3D1%26catalog%3Dlist"
        res=self._request(url)
        data=find(res,"""<div id="blogDetailDiv" style="font-size:14px;">""","""<img id="paperPicArea1""")
        data.strip()
        #replies=find(res,"""var g_oBlogData =""","""</script>""")
        #replies.replace(";","").strip()
        #return {'data':data,'relist':replies}
        return data


    def dolikeblog(self,uin,blogid):
        """赞日志"""
        url="http://w.qzone.qq.com/cgi-bin/likes/internal_dolike_app?g_tk=%s"%self.gtk
        key='http://user.qzone.qq.com/%s/blog/%s'%(uin,blogid)
        data={'qzreferrer':None,#http://user.qzone.qq.com/1985170374?ptlang=2052#!app=2&via=QZ.HashRefresh&pos=1365338398
            'opuin':self.qq,
            'unikey':key,
            'curkey':key,
            'from':2,
            'fupdate':1,
            'face':0
            }
        res=self._request(url,data)
        if res.find("succ"):
            return res
        else:
            return

    def add_comment_blog(self,uin,blogid,msg):
        """回复日志"""
        try:msg=msg.encode('gbk')
        except:pass
        url="http://b11.qzone.qq.com/cgi-bin/blognew/add_comment?g_tk=%s" %self.gtk
        data={'qzreferrer':None,#'http://b11.qzone.qq.com/cgi-bin/blognew/blog_output_data?uin=1149757929&blogid=1327142920&styledm=ctc.qzonestyle.gtimg.cn&imgdm=ctc.qzs.qq.com&bdm=b.qzone.qq.com&mode=2&numperpage=15&blogseed=0.4649679937865585&property=GoRE&timestamp=1372856149&dprefix=&g_tk=1629993971&page=1&refererurl=http%3A%2F%2Fctc.qzs.qq.com%2Fqzone%2Fapp%2Fblog%2Fv6%2Fbloglist.html%23nojump%3D1%26page%3D1%26catalog%3Dlist&ref=qzone',
            'uin':self.qq,
            'content':msg,
            'topicId':'%s_%s'%(uin,blogid),
            'yscProp':'0',
            'property':'GoRE',
            'source':'45',
            'iNotice':'1',
            'inCharset':'gbk',
            'outCharset':'gbk',
            'format':'fs',
            'ref':'qzone',
            'json':'1',
            'g_tk':self.gtk,
            'secverifykey':'28Q1206%s_%s'%(uin,self.qq)
        }
        res=self._request(url,data)
        return res

    def get_taotao(self,uin,posmax=100):
        """获取心情"""
        SETP=20
        rlist=range(0,posmax,SETP) if SETP <= posmax else range(0,posmax)
        self._headers.update({"Referer":"http://ctc.qzs.qq.com/qzone/app/blog/v6/bloglist.html"})
        msglist=[]
        for pos in rlist:
            url="http://sh.taotao.qq.com/cgi-bin/emotion_cgi_feedlist_v6?uin=%s&hostUin=%s&g_tk=%s&pos=%s"%(uin,uin,self.gtk,pos) \
            +"&inCharset=utf-8&outCharset=utf-8&notice=0&sort=0&num=20&cgi_host=http%3A%2F%2Fsh.taotao.qq.com%2Fcgi-bin%2Femotion_cgi_feedlist_v6&code_version=1&format=json"
            res=self._request(url)
            try:msglist+=json.loads(res)['msglist']
            except:break
        return msglist
        """"{"certified":0,
            "cmtnum":0,
            "conlist":[{"con":"这是一个测试","type":2}],
            "content":"这是一个测试",
            "createTime":"2013-07-03 20:36:29",
            "created_time":1372854989,
            "fwdnum":0,
            "has_more_con":0,
            "issigin":0,
            "lbs":{"id":"","idname":"","name":"","pos_x":"","pos_y":""},
            "name":"WallE",
            "pic_template":"",
            "replies":0,
            "right":1,
            "rt_sum":0,
            "secret":0,
            "source_appid":"",
            "source_name":"",
            "source_url":"",
            "t1_source":1,
            "t1_subtype":1,
            "t1_termtype":0,
            "tid":"c64b5376cd1ad4516db80a00",
            "ugc_right":1,
            "uin":1985170374,
            "wbid":0},
        """

    def doliketaotao(self,uin,tid):
        """赞说说"""
        url="http://w.qzone.qq.com/cgi-bin/likes/internal_dolike_app?g_tk=%s"%self.gtk
        data={'qzreferrer':None,#"http://user.qzone.qq.com/%s/main#!app=311&url=http%3A%2F%2Fctc.qzs.qq.com%2Fqzone%2Fapp%2Fmood_v6%2Fhtml%2Findex.html%3Ftab%3Dmine%26uin%3D%s"%(uin,uin),
              'opuin':self.qq,
              'unikey':'http://user.qzone.qq.com/1985170374/mood/%s.1'%tid,
              'curkey':'http://user.qzone.qq.com/1985170374/mood/%s.1'%tid,
              'from':'-100',
              'fupdate':1,
              'face':0,
             }
        res=self._request(url,data)
        return res

    def add_comment_taotao(self,uin,tid,msg):
        """回复说说"""
        self._headers.update({'DNT':1})
        self._headers.update({'Host':'user.qzone.qq.com'})
        self._headers.update({'Origin':'http://user.qzone.qq.com'})
        self._headers.update({'X-Real-Url':'http://taotao.qq.com/cgi-bin/emotion_cgi_addcomment_ugc?g_tk=%s'%self.gtk})
        self._headers.update({'Referer':'http://user.qzone.qq.com/%s/main'%uin})
        self._headers.update({'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36 CoolNovo/2.0.9.20'})
        url="http://user.qzone.qq.com/q/taotao/cgi-bin/emotion_cgi_addcomment_ugc?g_tk=%s"%self.gtk
        data={'topicId':'%s_%s__1'%(uin,tid),
            'feedsType':'100',
            'inCharset':'utf-8',
            'outCharset':'utf-8',
            'plat':'qzone',
            'source':'ic',
            'hostUin':uin,
            'isSignIn':'',
            'uin':self.qq,
            'format':'fs',
            'ref':'feeds',
            'content':msg,
            'richval':'',
            'richtype':'',
            'private':0,
            'paramstr':2,
            'qzreferrer':'http://user.qzone.qq.com/%s/main'%uin,
             }
        res=self._request(url,data)
        return res
        '''
        <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><script type="text/javascript">
        document.domain="qq.com";
        frameElement.callback({"code":0,"data":{"content":"@{uin:1067679224,nick:空空,who:1} test","id":3,"postTime":1414210419},
        "err":{"code":0,"ret":0},"message":"",
        "result":{"smoothpolicy":{"comsw.disable_soso_search":0,"l1sw.read_first_cache_only":0,"l2sw.dont_get_reply_cmt":0,
        "l2sw.mixsvr_frdnum_per_time":50,"l3sw.hide_reply_cmt":0,"l4sw.read_tdb_only":0,"l5sw.read_cache_only":0}},
        "retTid":3,"subcode":0,"tid":3});
        </script></body></html>
        '''

    def get_visitor_blog(self,uin,id):
        id=str(id)
        """获取日志或说说浏览记录"""
        aid=202 if re.match(r"\d+$",id) else 311   #日志202 说说311
        url="http://g.qzone.qq.com/cgi-bin/friendshow/cgi_get_visitor_single?appid=%s&uin=%s&blogid=%s&param=%s&ref=qzfeeds&g_tk=%s"%(aid,uin,id,id,self.gtk)
        res=self._request(url)
        try:
            return json.loads(res.split("back(")[1].split(");")[0])['data']['list']
        except:
            return
        """{"uin":515427575,"name":"李仁华"}"""

    def get_visitor_main(self,uin):
        """获取最近访客信息"""
        url=="http://g.qzone.qq.com/cgi-bin/friendshow/cgi_get_visitor_simple?page=1&fupdate=1&mask=3&uin=%s&g_tk=%s" %(uin,self.gtk)
        res=self._request(url)
        try:
            return json.loads(res.split("back(")[1].split(");")[0])['data']['liems']
        except:
            return
        """
        """

    def get_userinfo(self,uin):
        url="http://base.s2.qzone.qq.com/cgi-bin/user/cgi_userinfo_get_all?fupdate=1&uin=%s&vuin=%s&g_tk=%s&rd=%s"%(uin,self.qq,self.gtk,random.Random().random())
        res=self._request(url)
        try:
            return json.loads(res.split("back(")[1].split(");")[0])['data']
        except:
            return
    def tfriend(self,uin,msg):
        '''?申请访问空间'''
        url="http://w.qzone.qq.com/cgi-bin/tfriend/applyentryright.cgi?g_tk=%s"%self.gtk
        data={'hUin':uin,
              'vUin':self.qq,
              'strmsg':msg,
              'fupdate':1,
              'rd':random.Random().random(),
          }
        res=self._request(url,data)
        return res

    def send_refeeds(self,uin,id,msg):
        '''发表心情回复'''
        url = "http://user.qzone.qq.com/q/taotao/cgi-bin/emotion_cgi_re_feeds?g_tk=%s"%self.gtk
        data = {'topicId':id, #1067679224_f87da33f5e6d4a54736a0700__1
                'feedsType':102,
                'inCharset':'utf-8',
                'outCharset':'utf-8',
                'plat':'qzone',
                'source':'ic',
                'hostUin':None,
                'isSignIn':None,
                'uin':self.qq,
                'format':'fs',
                'ref':'feeds' ,
                'content':msg, #'@{uin:1162042617,nick:女神,auto:1} 女神快加我QQ'
                'commentId':1,
                'commentUin':uin,
                'richval':None ,
                'richtype':None ,
                'private':0,
                'paramstr':1,
                'qzreferrer':'http://user.qzone.qq.com/%s/infocenter'%self.qq ,
        }
    '''
    最近相片
    http://tipsimage2.qq.com/cgi-bin/cgi_get_tips?uin=173446570&refer=qzone&ver=5&g_tk=1032993261

    def get_isonline(self,*uinlist):
        url="http://qzonebit.store.qq.com/qlogo_list.cgi?count=1&uins=1495031454%2C1141094489&g_tk=15025320"
    def get_userinfo(self,uin):
        """个人资料"""
        self._headers.update({"Referer":"http://ctc.qzs.qq.com/qzone/profile/index.html?tab=info"})
        url="http://base.s2.qzone.qq.com/cgi-bin/user/cgi_userinfo_get_all?fupdate=1&uin=%s&vuin=%s&g_tk=%s&rd=%s"%(uin,self.qq,self.gtk,random.Random().random())
        res=self._request(url)
        return res
   def get_blog_friendshow(self,blogid):
        self._headers.update({"Referer":"http://ctc.qzs.qq.com/qzone/app/blog/v6/bloglist.html"})
        http://g.qzone.qq.com/cgi-bin/friendshow/cgi_get_visitor_simple?uin=1149757929&mask=2&mod=1&contentid=1327142920&fupdate=1&g_tk=1629993971
    def get_comment(self,blogid):
        self._headers.update({"Referer":"http://ctc.qzs.qq.com/qzone/app/blog/v6/bloglist.html"})
        http://b11.qzone.qq.com/cgi-bin/blognew/get_comment_list?uin=664284092&num=15&topicId=1149757929_1327142920&start=0&r=0.24495175876654685&iNotice=1&inCharset=gbk&outCharset=gbk&format=jsonp&ref=qzone&g_tk=1629993971
名片http://r.qzone.qq.com/cgi-bin/user/cgi_personal_card?uin=664284092&fupdate=1&g_tk=950432105&rd=1373372141

'''


def hito():
    url="http://api.hitokoto.us/rand"
    res=eval(request.urlopen(url).read())["hitokoto"]
    return res

if __name__=="__main__":
    import sys,os
    sys.path.append('..')
    import util
    if not os.path.exists(util.getpath('res')):
        os.mkdir(util.getpath('res'))

    Q=QZONE('664284092','')
    while 1:
        print(
            Q.add_comment_taotao(1067679224,'f87da33f5e6d4a54736a0700',input('#'))
        )



    '''bloglist=Q.get_taotao(664284092)
    for blog in bloglist:
        print(Q.add_comment_blog(664284092,blog['tid'],blog['created_time']))
        input()'''






    '''
            #Q.send_taotao(u"给%s留言:%s"%(friend['uin'],msg))
            #pprint(friend['uin'],msg)

            bloglist=Q.get_blogid(friend['uin'])
            #pprint(bloglist)
            for blog in bloglist:
                #msg=hito()
                #Q.dolikeblog(friend['uin'],blog['blogId'])
                #Q.add_comment_blog(friend['uin'],blog['blogId'],msg)
                #pprint(friend['uin'],blog['blogId'],msg)
                threading.Thread(target=Q.add_comment_blog, args=(friend['uin'],blog['blogId'],hito(),)).start()

            taotaolist=Q.get_taotao(friend['uin'])
            #pprint(taotaolist)
            for taotao in taotaolist:
                #msg=hito()
                #Q.doliketaotao(friend['uin'],taotao['tid'])
                #Q.add_comment_taotao(friend['uin'],taotao['tid'],msg)
                #pprint(friend['uin'],taotao['tid'],msg)
                threading.Thread(target=Q.add_comment_taotao, args=(friend['uin'],taotao['tid'],hito(),)).start()
        '''

